package com.zfl.thread.day02;

import lombok.AllArgsConstructor;
import lombok.Data;

class Bank {
    int balance=1000;

    public synchronized void withdraw(int money) {
        if(balance<money){
            System.out.println(Thread.currentThread().getName()+"取款失败，余额不足");
        } else{
            this.balance-=money;
            System.out.println(Thread.currentThread().getName()+"取款["+money+"]，余额["+this.balance+"]");
        }
    }

    public synchronized void deposit(int money) {
        this.balance += money;
        System.out.println(Thread.currentThread().getName()+"存款["+money+"]，余额["+this.balance+"]");
    }
}

@Data
@AllArgsConstructor
class TicketThread implements Runnable {

    Bank bank;

    @Override
    public void run() {
        for (int i = 0; i < 30; i++) {
            if(i%2==0){
                bank.withdraw(300);
            } else {
                bank.deposit(200);
            }
            // 关键：每次操作后休眠一小段时间，释放CPU，给其他线程机会
            try {
                Thread.sleep(10); // 休眠10毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class SynchronizedDemo03 {
    public static void main(String[] args) {
        Bank bank = new Bank();
        new Thread(new TicketThread(bank),"用户1").start();
        new Thread(new TicketThread(bank),"用户2").start();
        new Thread(new TicketThread(bank),"用户3").start();
        new Thread(new TicketThread(bank),"用户4").start();
        new Thread(new TicketThread(bank),"用户5").start();
    }
}
